package com.orange.core.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.orange.core.pojo.entity.ICreateModel;
import com.orange.core.pojo.entity.IUpdateModel;
import com.orange.core.util.Constants;
import com.orange.core.util.PrincipalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@Component
public class OperatorMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object object = metaObject.getOriginalObject();
        Integer operatorId = Optional.ofNullable(PrincipalUtil.getId()).orElse(0);
        if (!(object instanceof ICreateModel || object instanceof IUpdateModel)) {
            log.warn("当前类 {} 未实现ICreateModel/IUpdateModel接口，不能使用自动填充功能", object.getClass());
            return;
        }
        if (object instanceof ICreateModel) {
            setFieldValByName(Constants.CREATOR_FIELD, operatorId, metaObject);
        }
        if (object instanceof IUpdateModel) {
            setFieldValByName(Constants.MODIFIER_FIELD, operatorId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object object = metaObject.getOriginalObject();
        if (object instanceof IUpdateModel) {
            Integer operatorId = Optional.ofNullable(PrincipalUtil.getId()).orElse(0);
            setFieldValByName(Constants.MODIFIER_FIELD, operatorId, metaObject);
        } else {
            log.warn("当前类 {} 未实现IUpdateModel接口，不能使用自动填充功能", object.getClass());
        }
    }
}
